<?php
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\model\Member;
use app\admin\model\User;
use app\admin\model\Task;
use app\admin\model\Standard;
use app\admin\model\SportRecord;
use app\admin\model\Grade;
use app\admin\model\Departments;
use app\admin\model\Professional;
use app\admin\model\Clss;
use app\admin\model\Project;
use app\admin\model\School;
use app\admin\model\TaskscoreRecord;

/**
 * 系统登录-控制器
 * @author 牧羊人
 * @since 2020/11/19
 * Class WechatminiLogin
 * @package app\admin\controller
 */
class Wechatmini extends Backend
{
    /**
     * 初始化
     * @author 牧羊人
     * @since 2020/11/19
     */
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model1 = new Member();
        $this->model2 = new User();
        
    }

    /**
     * 个人资料
     * @return mixed
     * @since 2020/11/14
     * @author 牧羊人
     */
    public function userinfo()
    {
        $userId = $this->model1->userId();//获取当前userid
        //$usertype = explode("_", $userId);
        // if ($usertype[1]==1) {//学生登录
        //     $userInfo = $this->model2->getInfo(intval($usertype[0]));
        // }

        // if ($usertype[1]==2) {//老师登录
        //     $userInfo = $this->model2->getInfo($usertype[0]);
        // }
        $userInfo = $this->model2->getInfo($userId);
        $class = new Clss();
        if ($userInfo['user_type']==2) {//学生登录
            $memberId = $this->model1->where('roll',$userInfo['username'])->whereOr('username',$userInfo['username'])->value('id');
            $userInfo = $this->model1->getInfo($memberId);
            $userInfo['tiyulist'] = [];
            if ($userInfo['features']) {
                $features = json_decode($userInfo['features'],true);
                $tiyuclss = [];
                foreach ($features as $key => $val) {
                    $clks = $class->where('id',intval($val))->find();
                    $tiyuclss[$key]['name'] = $clks['name'];
                    $tiyuclss[$key]['header'] = $clks['header'];
                    $tiyuclss[$key]['mobile'] = $this->model2->where('id',$clks['head'])->value('mobile');
                }
                $userInfo['tiyulist'] = $tiyuclss;
            }
            $userInfo['user_type'] = 2;
        }else{
            $userInfo['classlist'] = $class->where('head',$userId)->select();
        }
        return $this->jsonReturn(message('获取成功', true, $userInfo));
    }

    /**
     * 未完成任务数量
     * @return mixed
     * @since 2020/11/14
     * @author 牧羊人
     */
    public function wei()
    {
        $userId = $this->model2->userId();//获取当前userid
        $userInfo = $this->model2->getInfo($userId);
        $task = new Task();
        
        $map =[];
        
        if ($userInfo['user_type']==2) {//学生
            $features = $this->model1->where('roll',$userInfo['username'])->value('features');
            //$memberInfo = $this->model1->getInfo($memberId);
            $fearr = json_decode($features,true);
            $like = [];
            foreach ($fearr as $vv) {
                $like[] = ['like','%'.$vv.'%'];
                
            }
            if (count($like)>1) {
                $map[] = ['class',$like,'or'];
            }else{
                if (count($like)>0) {
                    $map[] = ['class',$like];
                }
                
            }
        }else{//老师
            $map[] = ['create_user','=',$userInfo['id']];
        }
        
        $uncompletedCount = $task->where($map)->where(['status'=>1])->count();
        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "uncompletedCount" => $uncompletedCount,
        );
        return $this->jsonReturn($message);
    }

    /**
     * 我的任务
     * @return mixed
     * @since 2020/11/14
     * @author 牧羊人
     */
    public function task()
    {
        $params = input();
        $userId = $this->model2->userId();//获取当前userid
        $userInfo = $this->model2->getInfo($userId);
        //$usertype = explode("_", $userId);
        $page = isset($params['page'])&&is_numeric($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['pageSize'])&&is_numeric($params['pageSize']) ? $params['pageSize'] : 10;
        $task = new Task();
        $map =[];
        if (isset($params['status'])&&$params['status']) {
            $map[] = ['status','=',$params['status']];
        }
        if ($userInfo['user_type']==2) {//学生
            $features = $this->model1->where('roll',$userInfo['username'])->value('features');
            //$memberInfo = $this->model1->getInfo($memberId);
            $fearr = json_decode($features,true);
            $like = [];
            foreach ($fearr as $vv) {
                $like[] = ['like','%'.$vv.'%'];
                
            }
            if (count($like)>1) {
                $map[] = ['class',$like,'or'];
            }else{
                if (count($like)>0) {
                    $map[] = ['class',$like];
                }
                
            }
            
            
            $result = $task->where($map)->order('id desc')
            ->page($page, $pageSize)->column("id");
        }else{//老师
            $map[] = ['create_user','=',$userInfo['id']];
            $result = $task->where($map)->order('id desc')
            ->page($page, $pageSize)->column("id");
        }
        $list = [];
        if (is_array($result)) {
            foreach ($result as $k=>$val) {
                $info = $task->getInfo($val);
                $list[] = $info;
            }
        }
        foreach ($list as &$va) {
            $va['create_time'] = date('Y-m-d H:i:s',$va['create_time']);
        }
        unset($va);
        $count = $task->where($map)->count();
        // 过滤条件的回调函数
        $callback = function($item) {
            return $item[0]!='status';
        };

        // 使用 array_filter 进行过滤
        $result = array_filter($map, $callback);
        $map2 = [];
        foreach ($result as $vv) {
            $map2[] = $vv;
        }
        $uncompletedCount = $task->where($map2)->where(['status'=>1])->count();
        $completedCount = $task->where($map2)->where(['status'=>2])->count();
        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "uncompletedCount" => $uncompletedCount,
            "completedCount" => $completedCount,
            "last_page" => ceil($count/$pageSize)
        );
        return $this->jsonReturn($message);
    }

    /**
     * 任务成绩
     * @return mixed
     * @since 2020/11/14
     * @author 牧羊人
     */
    public function taskrecord()
    {
        $params = input();
        $id = input('post.id');
        $projectId = input('post.projectId');
        $userId = $this->model2->userId();//获取当前userid
        $userInfo = $this->model2->getInfo($userId);
        // $usertype = explode("_", $userId);
        $page = isset($params['page'])&&is_numeric($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['pageSize'])&&is_numeric($params['pageSize']) ? $params['pageSize'] : 10;
        $sportrecord = new TaskscoreRecord();
        $map = [];
        // 更新时间
        $starttime = isset($params['starttime']) ? trim($params['starttime']) : '';
        $endtime = isset($params['endtime']) ? trim($params['endtime']) : '';
        if ($starttime&&$endtime) {
            if ($starttime==$endtime) {
                $endtime = date('Y-m-d 23:59:59',strtotime($endtime));
            }
            $map[] =  ['createdDate', 'between time', [$starttime, $endtime]];
        }
        // 排序
        $sort = isset($params['sort']) && $params['order'] ? $params['sort'] . ' ' . $params['order'] : 'pingscore desc';
        if ($userInfo['user_type']==2) {//学生
            $memberId = $this->model1->where('roll',$userInfo['username'])->value('id');
            // $memberId = $this->model1->where('roll','2023130142')->value('id');
            
            if ($projectId) {
                $map[] = ['projectId','=',$projectId];
            }
            
            if ($id) {
                $map[] = ['taskId','=',intval($id)];
            }
            
            $map[] = ['memberId','=',$memberId];
            $result = $sportrecord->where($map)->order($sort)->group('memberId')->group('projectId')->page($page, $pageSize)->field('MAX(pingscore) as pingscore')->column("id");
            //$list = $sportrecord->getList($map,'id desc',($page - 1)*$pageSize.','.$pageSize);
        }else{ //老师
            if ($id) {
                $map[] = ['taskId','=',intval($id)];
            }
            $result = $sportrecord->where($map)->order($sort)->group('memberId')->group('projectId')->page($page, $pageSize)->field('MAX(pingscore) as pingscore')->column("id");
            //$list = $sportrecord->getList($map,'id desc',($page - 1)*$pageSize.','.$pageSize);
        }
        $list = [];
        if (is_array($result)) {
            foreach ($result as $val) {
                $info = $sportrecord->getInfo($val);
                $list[] = $info;
            }
        }

        $count = $sportrecord->where($map)->group('memberId')->group('projectId')->count();
        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
        return $this->jsonReturn($message);
    }

    /**
     * 添加任务
     * @return mixed
     * @since 2020/11/14
     * @author 牧羊人
     */
    public function addtask()
    {
        $params = input();
        $task = new Task();
        $class = new Clss();
        $params['status']=1;
        if ($params['class']) {
            $carr = json_decode($params['class'],true);
            $cinfo = $class->where('id',$carr[0])->find();
            $params['organization'] = $cinfo['organization'];
            $params['grade'] = $cinfo['grade'];
            $params['superior'] = $cinfo['superior'];
            $params['professional'] = $cinfo['professional'];
        }
        $info = $task->edit($params);
        if ($info) {
            return $this->jsonReturn(message("添加成功", true));
        }
    }

    /**
     * 删除任务
     * @return mixed
     * @since 2020/11/14
     * @author 牧羊人
     */
    public function deltask()
    {
        $id = input('id/d');
        $task = new Task();
        $info = $task->drop($id);
        if ($info) {
            return $this->jsonReturn(message("删除成功", true));
        }
    }

    public function getProjectList()
    {
        $userId = $this->model2->userId();//获取当前userid
        $userInfo = $this->model2->getInfo($userId);
        if ($userInfo['user_type']==2) {
            return $this->jsonReturn(message("权限不足", false));
        }
        $where = [];
        $where['mark'] = 1;
        $list = [];
        if (!$userInfo['schoolId']) {
            return $this->jsonReturn(message("未绑定学校", false));
        }
        $where['organization'] = $userInfo['schoolId'];
        $project = new Project();
        $list = $project->where($where)->select()->toArray();
        return $this->jsonReturn(message("操作成功", true, $list));
    }

    public function getClassList()
    {
        $userId = $this->model2->userId();//获取当前userid
        $userInfo = $this->model2->getInfo($userId);
        if ($userInfo['user_type']==2) {
            return $this->jsonReturn(message("权限不足", false));
        }
        $where = [];
        $where['mark'] = 1;
        $list = [];
        if (!$userInfo['departmentsId']) {
            return $this->jsonReturn(message("未绑定院系", false));
        }
        $where['superior'] = $userInfo['departmentsId'];
        $class = new Clss();
        $list = $class->where($where)->select()->toArray();
        return $this->jsonReturn(message("操作成功", true, $list));
    }

    public function getStandardList()
    {
        $userId = $this->model2->userId();//获取当前userid
        $userInfo = $this->model2->getInfo($userId);
        if ($userInfo['user_type']==2) {
            return $this->jsonReturn(message("权限不足", false));
        }
        $where = [];
        $where['mark'] = 1;
        $list = [];
        if (!$userInfo['schoolId']) {
            return $this->jsonReturn(message("未绑定学校", false));
        }
        $where['organization'] = $userInfo['schoolId'];
         if (!$userInfo['departmentsId']) {
            return $this->jsonReturn(message("未绑定院系", false));
        }
        $where['superior'] = $userInfo['departmentsId'];
        $standard = new Standard();
        $list = $standard->where($where)->select()->toArray();
        return $this->jsonReturn(message("操作成功", true, $list));
    }

    /**
     * 手环管理
     * @return mixed
     * @since 2020/11/14
     * @author 牧羊人
     */
    public function braceletlist()
    {
        $params = input();
        $userId = $this->model2->userId();//获取当前userid
        //$usertype = explode("_", $userId);
        $page = isset($params['page'])&&is_numeric($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['pageSize'])&&is_numeric($params['pageSize']) ? $params['pageSize'] : 10;
        $class = new Clss();
        
        $map =[];
        $map[] = ['mark','=',1];
        // if (isset($params['status'])&&$params['status']) {
        //     $map[] = ['status','=',$params['status']];
        // }
        if ($userId) {
            $map[] = ['head','=',$userId];
        }
        $list = $class->getList($map,'id desc',($page - 1)*$pageSize.','.$pageSize);
        $member = new Member();
        foreach ($list as &$val) {
            $where = [];
            $where[] = ['mark','=',1];
            $str = '"'.$val['id'].'"';
            $where[] = ['features', 'like','%'.$str.'%'];
             //班级人数
             $val['classnum'] = $member->where($where)->count();
             //已绑定手环人数
             $where[] = ['bracelet','<>',''];
             $val['braceletnum'] = $member->where($where)->count();
        }
        unset($val);
        $count = $class->where($map)->count();
        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "clazzcount" => $count,
            "last_page" => ceil($count/$pageSize)
        );
        return $this->jsonReturn($message);
    }

    /**
     * 设置手环状态
     * @return mixed
     * @since 2020/11/19
     * @author 牧羊人
     */
    public function braceletstatus()
    {
        // 参数
        $param = request()->param();
        $class = new Clss();
        // 记录ID
        $ids = getter($param, "id");
        if (empty($ids)) {
            return $this->jsonReturn(message("记录ID不能为空", false));
        }
        if (is_array($ids)) {
            // 批量操作
            $result = $class->setDAll($ids,$param['braceletstatus']);
            if (!$result) {
                return $this->jsonReturn(message("设置失败", false));
            }
            return $this->jsonReturn(message("设置成功"));
        }else{
            $error = '';
            $item = [
                'id' => $param['id'],
                'braceletstatus' => $param['braceletstatus']
            ];
            if ($param['braceletstatus']==1) {
                $item['bracelet_start'] = time();
                $item['bracelet_end'] = 0;
            }
            if ($param['braceletstatus']==0) {
                $item['bracelet_end'] = time();
            }
            $rowId = $class->edit($item, $error);
            if (!$rowId) {
                return $this->jsonReturn(message($error, false));
            }
            return $this->jsonReturn(message());
        }
        
    }

    /**
     * 手环名单
     * @return mixed
     * @since 2020/11/14
     * @author 牧羊人
     */
    public function braceletView()
    {
        // 参数
        $params = request()->param();
        $page = isset($params['page'])&&is_numeric($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['pageSize'])&&is_numeric($params['pageSize']) ? $params['pageSize'] : 10;
        $member = new Member();
        $list = [];
        $where = [];
        $where[] = ['mark','=',1];
        $str = '"'.$params['id'].'"';
        $where[] = ['features', 'like','%'.$str.'%'];
        $result = $member->where($where)->page($page, $pageSize)->column("id");
        if (is_array($result)) {
            foreach ($result as $val) {
                $info = $member->getInfo($val);
                $list[] = $info;
            }
        }
         //班级人数
         $classnum = $member->where($where)->count();
         //未绑定手环人数
         $where[] = ['bracelet','=',''];
         $braceletnum = $member->where($where)->count();
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "classnum" => $classnum,
            "braceletnum" => $braceletnum,
            "last_page" => ceil($classnum/$pageSize)
        );
        return $this->jsonReturn($message);
    }

}